﻿namespace BizCollegeWebApp.Controllers
{
    using System;
    using System.Linq;
    using System.Web.Mvc;
    using BizCollegeWebApp.Models;

    public class SurveyController : Controller
    {
        private BizCollegeDBDataContext db = new BizCollegeDBDataContext();

        // GET: /Survey/
        public ActionResult Index(string SearchSurvey)
        {
            // Temp:

            if (string.IsNullOrEmpty(SearchSurvey))
            {
                ViewBag.SearchSurvey = string.Empty;
            }
            else
            {
                ViewBag.SearchSurvey = SearchSurvey;
            }

            return View(this.db.GetSurveys(SearchSurvey).AsEnumerable());
        }

        // GET: /Survey/Details/5
        public ActionResult Details(int id)
        {
            Survey dbS = this.db.Surveys.FirstOrDefault(ss => ss.ID == id);
            if (dbS == null)
            {
                return RedirectToAction("Index");
            }

            return View(dbS);
        }

        public ActionResult Results(int courseId)
        {
            return View(this.db.SurveyReponses.Where(s => s.CourseID == courseId));
        }

        public ActionResult ResponseDetails(int responseId)
        {
            IQueryable<SurveyResponseModel> data = from answer in this.db.QuestionAnswers.Where(q => q.ResponseID == responseId)
                                                   join question in this.db.SurveyQuestions on answer.QuestionID equals question.ID
                                                   select new SurveyResponseModel(question, answer);


            return View(data);
        }

        public ActionResult TakeSurvey(int courseId)
        {
            // Note: Currently courseId is ignored, will be used later when different survey per course functionality is added
            Survey dbS = this.db.GetCourseSurvey(courseId);
            if (dbS == null)
            {
                TempData["Message"] = "No active survey can be found";
                return RedirectToAction("Index");
            }

            SurveyReponse sr = new SurveyReponse()
            {
                CourseID = courseId,
                UserID = Current.User.ID,
                SurveyID = dbS.ID,
                DateFilled = DateTime.Now
            };
            this.db.SurveyReponses.InsertOnSubmit(sr);
            this.db.SubmitChanges();

            return RedirectToAction("AnswerQuestion", new { questionID = this.db.GetFirstQuestionIDOfSurver(dbS.ID), responseID = sr.ID });
        }

        [HttpGet]
        public ActionResult AnswerQuestion(int questionID, int responseID)
        {
            SurveyQuestion sq = this.db.SurveyQuestions.FirstOrDefault(s => s.ID == questionID);
            if (sq == null)
            {
                TempData["Message"] = "No answer with the specified ID was found";
                return RedirectToAction("Index");
            }

            return View(sq);
        }

        [HttpPost]
        public ActionResult AnswerQuestion(int questionID, int responseID, QuestionAnswer answer, string option)
        {
            try
            {
                // If this is multiple choice with single selectable
                if (!string.IsNullOrEmpty(option))
                {
                    answer.SetSelected(option);
                }

                this.db.QuestionAnswers.InsertOnSubmit(answer);
                this.db.SubmitChanges();
                int nextQuestionId = this.db.GetNextQuestionIdByResponse(responseID, questionID);
                if (nextQuestionId == Constants.INVALIDID)
                {
                    TempData["Message"] = "Thank you for filling the survey. Your opinion is important to us.";
                    return RedirectToAction("Index");
                }

                return RedirectToAction("AnswerQuestion", new { questionID = nextQuestionId, responseID = responseID });
            }
            catch (Exception ex)
            {
                TempData["Message"] = ex.Message;
            }

            return RedirectToAction("AnswerQuestion", new { questionID = questionID, responseID = responseID });
        }

        // GET: /Survey/Create
        [HttpGet]
        public ActionResult Create()
        {
            return View(new Survey());
        }

        // POST: /Survey/Create
        [HttpPost]
        public ActionResult Create(Survey survey, string qtype)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    this.db.DeactivateActiveSurveys();
                    survey.IsActive = true;
                    this.db.Surveys.InsertOnSubmit(survey);
                    this.db.SubmitChanges();
                    return RedirectToAction(this.QuestionActionName(qtype), new { surveyID = survey.ID });
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("ex", ex.Message);
            }

            return View(survey);
        }

        [HttpGet]
        public ActionResult AddEssayQuestion(int surveyID)
        {
            return View(string.Empty);
        }

        [HttpPost]
        public ActionResult AddEssayQuestion(int surveyID, string question, string qtype)
        {
            try
            {
                if (!string.IsNullOrEmpty(question) && this.db.Surveys.Any(s => s.ID == surveyID))
                {
                    this.db.SurveyQuestions.InsertOnSubmit(new SurveyQuestion()
                        {
                            QuestionText = question,
                            SurveryID = surveyID
                        });
                    this.db.SubmitChanges();

                    return RedirectToAction(this.QuestionActionName(qtype), new { surveyID = surveyID });
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("ex", ex.Message);
            }

            return View(question);
        }

        [HttpGet]
        public ActionResult AddMChoiceQuestion(int surveyID)
        {
            return View(new SurveyQuestion());
        }

        [HttpPost]
        public ActionResult AddMChoiceQuestion(int surveyID, SurveyQuestion question, string qtype)
        {
            try
            {
                if (ModelState.IsValid && this.db.Surveys.Any(s => s.ID == surveyID))
                {
                    question.SurveryID = surveyID;
                    this.db.SurveyQuestions.InsertOnSubmit(question);
                    this.db.SubmitChanges();

                    return RedirectToAction(this.QuestionActionName(qtype), new { surveyID = surveyID });
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("ex", ex.Message);
            }

            return View(question);
        }

        // GET: /Survey/Edit/5
        public ActionResult Edit(int id)
        {
            return View();
        }

        // POST: /Survey/Edit/5
        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: /Survey/Delete/5
        public ActionResult Delete(int id)
        {
            Survey dbS = this.db.Surveys.FirstOrDefault(ss => ss.ID == id);
            if (dbS == null)
            {
                return RedirectToAction("Index");
            }

            try
            {
                dbS.IsActive = false;
                this.db.SubmitChanges();
                TempData["Message"] = "Survey has been succefully deactivated";
            }
            catch (Exception ex)
            {
                TempData["Message"] = ex.Message;
            }

            return RedirectToAction("Index");
        }

        public ActionResult Activate(int id)
        {
            Survey dbS = this.db.Surveys.FirstOrDefault(ss => ss.ID == id);
            if (dbS == null)
            {
                return RedirectToAction("Index");
            }

            try
            {
                this.db.DeactivateActiveSurveys();
                dbS.IsActive = true;
                this.db.SubmitChanges();
                TempData["Message"] = "Survey has been succefully activated. Note: other active surveys are deactivated";
            }
            catch (Exception ex)
            {
                TempData["Message"] = ex.Message;
            }

            return RedirectToAction("Index");
        }

        // POST: /Survey/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        private string QuestionActionName(string qtype)
        {
            if (string.IsNullOrEmpty(qtype) || qtype.Contains("essay"))
            {
                return "AddEssayQuestion";
            }
            else
            {
                return "AddMChoiceQuestion";
            }
        }
    }
}
